package com.OnTimeTeam.OnTime;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.net.Uri;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class Preferences extends Activity{

	private String path;
	private ListView prefLV;
	private int backPressed;
	private TextView textMessage;
	private Toast toast;
	private ListsManagerAdapter listManagerAdapter;
	private EditText editBox;
	private ArrayList<String> ADDRESSES;
	private ArrayList<Boolean> fixedArray;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        setContentView(R.layout.pref);

        path = getApplicationContext().getFilesDir().getPath().toString();
        
        setToast();
        
        backPressed = 0;
        
        ArrayList<Boolean> items = new ArrayList<Boolean>();
        items.add(true);items.add(true);items.add(true);
        
        
        prefLV = (ListView) findViewById(R.id.prefLV);
        PrefLVAdapter prefAdapter = new PrefLVAdapter(getBaseContext(), R.layout.pref_item, items);
		prefLV.setAdapter(prefAdapter);
		
		//Define what happens when clicking an item in the List-view
		prefLV.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View v, int index, long id) {
				
				switch(index) {
				case 0:
					startActivity(new Intent(Preferences.this, DefaultsSetter.class));
					break;
				case 1:
					infoManager();
					break;	
				case 2:	
					connectToGooglePlay();
					break;
				}
				
			}
		});
	}
	
	void connectToGooglePlay() {
		
		final String appName = "com.OnTimeTeam.OnTime";
		
		try {
			startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id="+appName)));
		} catch (android.content.ActivityNotFoundException anfe) {
		    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id="+appName)));

		}
	}
	
	
	void infoManager(){
		
		final LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
		View infoManagerLayout = inflater.inflate(R.layout.string_list,null);
		infoManagerLayout.setBackgroundResource(R.drawable.another_background);
		
		ListView infoManagerLV = (ListView)infoManagerLayout.findViewById(R.id.optionsList);
		
		ArrayList<String> items = new ArrayList<String>();
		items.add(getResources().getString(R.string.labelsManager));
		items.add(getResources().getString(R.string.locationsHistoryManager));
		items.add(getResources().getString(R.string.favoritesLocationsManager));
		
		
		InfoManagerOptions adapter = new InfoManagerOptions(this, R.layout.string_list_item, items);
		infoManagerLV.setAdapter(adapter);
		
		final Dialog infoManagerDialog = new Dialog(this, R.style.GrowBottom);
		infoManagerDialog.requestWindowFeature(Window.FEATURE_LEFT_ICON);
		infoManagerDialog.setContentView(infoManagerLayout);
		infoManagerDialog.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.info_icon_dialog);
		infoManagerDialog.setTitle(getResources().getString(R.string.infoManager));
		infoManagerDialog.setCancelable(true);
		infoManagerDialog.setCanceledOnTouchOutside(false);

		infoManagerLV.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View v, int index, long id) {
				switch(index){
					case 0:
						labelsManager();
						break;
					case 1:
						locationsManager(getResources().getString(R.string.locationsHistoryManager), R.drawable.device_access_time);
						break;
					case 2:
						locationsManager(getResources().getString(R.string.favoritesLocationsManager), R.drawable.favorites_icon);
						break;
				}
			}
		});
		infoManagerDialog.show();
	}
	
	

	void locationsManager(final String sort, int iconID) {
		
		final LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
		View layout = inflater.inflate(R.layout.info_manager,null); // change layout xml to one lime repeat days
		layout.setBackgroundResource(R.drawable.another_background);
		
		ListView infoLV = (ListView)layout.findViewById(R.id.infoList);
		Button removeButton = (Button)layout.findViewById(R.id.removeButton);
		Button addButton = (Button)layout.findViewById(R.id.addButton);
		editBox = (EditText)layout.findViewById(R.id.editBox);
		
		String[] addresses = null;
		ADDRESSES = new ArrayList<String>();
		fixedArray = new ArrayList<Boolean>();
		
		if(sort.equals(getResources().getString(R.string.locationsHistoryManager))) {
			addresses = AddressAutoCompletionIO.getAllAddresses(path + "/addresses.xml");
			for (String s : addresses)  
				ADDRESSES.add(s);
		}
		else { //FAVORITES
			addresses = AddressAutoCompletionIO.getAllAddresses(path + "/favorites.xml");
			for (String s : addresses)  
				ADDRESSES.add(s);
		}
		
		for(int i = 0; i < addresses.length; ++i)
			fixedArray.add(false);
		
		listManagerAdapter = new ListsManagerAdapter(this, R.layout.day_item, ADDRESSES, fixedArray);
		infoLV.setAdapter(listManagerAdapter);
		
		final Dialog dialog = new Dialog(this, R.style.GrowBottom);
		dialog.requestWindowFeature(Window.FEATURE_LEFT_ICON);
		dialog.setContentView(layout);
		dialog.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, iconID);
		
		if(sort.equals(getResources().getString(R.string.locationsHistoryManager)))
			dialog.setTitle(getResources().getString(R.string.addAddressToHistory));
		else
			dialog.setTitle(getResources().getString(R.string.addAddressToFavorites));
		
		dialog.setCancelable(true);
		dialog.setCanceledOnTouchOutside(false);
		
		infoLV.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View v, int index, long id) {

				fixedArray.set(index, !fixedArray.get(index));
				listManagerAdapter.notifyDataSetChanged();
			}
		});
		
		removeButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				
				for(int i = 0; i < fixedArray.size(); ++i){
					if(fixedArray.get(i)) {
						
						if(sort.equals(getResources().getString(R.string.locationsHistoryManager)))
							AddressAutoCompletionIO.deleteAddress(path + "/addresses.xml", ADDRESSES.get(i));
						else
							AddressAutoCompletionIO.deleteAddress(path + "/favorites.xml", ADDRESSES.get(i));

						ADDRESSES.remove(i);
						fixedArray.remove(i);
						i-=1;
					}
				}
				listManagerAdapter.notifyDataSetChanged();
			}
		});
		
		addButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				
				//hide keyboard
				InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(editBox.getWindowToken(), 0);
				
				
				for(int i = 0; i < ADDRESSES.size(); ++i){
					if(editBox.getText().toString().equals(ADDRESSES.get(i))) {
							//set toast and return
							return;
					}
				}
				
				DefaultsAddAddressToLocationsAsyncTask findAddress = new DefaultsAddAddressToLocationsAsyncTask(Preferences.this, editBox.getText().toString(), sort);
				findAddress.execute();
			}
		});
		
		dialog.show();
	}
	
	public void addAddress(String address, String sort) {
		
		if(sort.equals(getResources().getString(R.string.locationsHistoryManager)))
			AddressAutoCompletionIO.addNewAddress(path + "/addresses.xml", address);
		else
			AddressAutoCompletionIO.addNewAddress(path + "/favorites.xml", address);
		
		ADDRESSES.add(0, editBox.getText().toString());
		fixedArray.add(0, false);
		editBox.setText("");
		
		listManagerAdapter.notifyDataSetChanged();
	}
	
	public void showToast(String message) {
		
		textMessage.setText(message);
		toast.show();
		
	}
	
	void setToast() {
		
		final LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View toastView = inflater.inflate(R.layout.costum_toast,null);
		textMessage = (TextView)toastView.findViewById(R.id.addressConfirmation);
		toast = new Toast(Preferences.this);
		toast.setView(toastView);
		toast.setGravity(Gravity.BOTTOM|Gravity.CENTER, 0, 150);
		toast.setDuration(Toast.LENGTH_SHORT);
   		
   		
	}
	
	void labelsManager() {
		
		final LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
		View layout = inflater.inflate(R.layout.info_manager,null); // change layout xml to one lime repeat days
		layout.setBackgroundResource(R.drawable.another_background);
		
		ListView infoLV = (ListView)layout.findViewById(R.id.infoList);
		Button removeButton = (Button)layout.findViewById(R.id.removeButton);
		Button addButton = (Button)layout.findViewById(R.id.addButton);
		final EditText editBox = (EditText)layout.findViewById(R.id.editBox);
		
		String[] labels = LabelAutoCompletionIO.getAllLabels(path + "/labels.xml");
		
		final ArrayList<String> LABELS = new ArrayList<String>();
		for (String s : labels)  
			LABELS.add(s);
		
		final ArrayList<Boolean> fixedArray = new ArrayList<Boolean>();
		for(int i = 0; i < labels.length; ++i)
			fixedArray.add(false);
		final ListsManagerAdapter listManagerAdapter = new ListsManagerAdapter(this, R.layout.day_item, LABELS, fixedArray);
		infoLV.setAdapter(listManagerAdapter);
		
		final Dialog dialog = new Dialog(this, R.style.GrowBottom);
		dialog.requestWindowFeature(Window.FEATURE_LEFT_ICON);
		dialog.setContentView(layout);
		dialog.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.label);
		dialog.setTitle(getResources().getString(R.string.labelsManager));
		dialog.setCancelable(true);
		dialog.setCanceledOnTouchOutside(false);
		
		infoLV.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View v, int index, long id) {

				fixedArray.set(index, !fixedArray.get(index));
				listManagerAdapter.notifyDataSetChanged();
			}
		});
		
		removeButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				
				for(int i = 0; i < fixedArray.size(); ++i){
					if(fixedArray.get(i)) {
						
						LabelAutoCompletionIO.removeLabel(path + "/labels.xml", LABELS.get(i));
						LABELS.remove(i);
						fixedArray.remove(i);
						i-=1;
					}
				}
				listManagerAdapter.notifyDataSetChanged();
			}
		});
		
		addButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				
				InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(editBox.getWindowToken(), 0);
				
				for(int i = 0; i < LABELS.size(); ++i){
					if(editBox.getText().toString().equals(LABELS.get(i))) {
						
							//set toast and return
							return;
							
					}
				}
				
				LabelAutoCompletionIO.addNewLabel(path + "/labels.xml", editBox.getText().toString());
				LABELS.add(0, editBox.getText().toString());
				fixedArray.add(0, false);
				editBox.setText("");
				//delete label from file also
				
				listManagerAdapter.notifyDataSetChanged();
			}
		});
		
		dialog.show();
	}


	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if (keyCode == KeyEvent.KEYCODE_BACK) {
	    	
	    	backPressed+=1;
			
			if(backPressed == 1)  {
				showToast(getResources().getString(R.string.pressBack));
			}
			else if(backPressed == 2)
				onBackPressed();

			new java.util.Timer().schedule( 
			        new java.util.TimerTask() {
			            public void run() {
			            	backPressed = 0;
			            }
			        }, 
			        2000 
			);
			
	        return true;
	    }
	    return super.onKeyDown(keyCode, event);
	}
	


}
